/**
 * @file simple-popover
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {findDOMNode} from 'react-dom';
import * as assign from 'object-assign';
import * as cx from 'classnames';


import './simple-popover.scss';

export default class SimplePopOver extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    placement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
    positionTop: PropTypes.oneOfType([
      PropTypes.number, PropTypes.string
    ]),
    positionLeft: PropTypes.oneOfType([
      PropTypes.number, PropTypes.string
    ]),
    offset: PropTypes.oneOfType([
      PropTypes.func,
      PropTypes.shape({
        x: PropTypes.number,
        y: PropTypes.number
      })
    ])
  };

  static defaultProps = {
    className: 'simple-popover',
    autoScrollIntoView: false
  };

  state = {
    xOffset: 0,
    yOffset: 0
  };

  componentDidMount() {
    this.mayUpdateOffset();
    this.props.autoScrollIntoView && setTimeout(() => {
      findDOMNode(this).scrollIntoView();
    }, 200);
  }

  componentDidUpdate() {
    this.mayUpdateOffset();
  }

  mayUpdateOffset() {
    let offset = this.props.offset;

    if (offset && typeof offset === 'function') {
      const {
        placement,
        positionTop: y,
        positionLeft: x
      } = this.props;
      offset = offset(findDOMNode(this).getBoundingClientRect(), {
        x, y, placement
      });
    }

    this.setState({
      xOffset: offset ? offset.x : 0,
      yOffset: offset ? offset.y : 0
    });
  }

  render() {
    const {
      placement,
      positionTop,
      positionLeft,
      className,
      style,
      children,
    } = this.props;


    const classes = {
      [placement]: true
    };

    const {
      xOffset,
      yOffset
    } = this.state;

    const outerStyle = assign({
      display: 'block'
    }, style, {
      top: positionTop + yOffset,
      left: positionLeft + xOffset
    });

    return (
      <div
        className={cx('simple-popover', className, classes)}
        style={outerStyle}
      >
        {children}
      </div>
    );
  }
}
